/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useState, useEffect } from 'react';
import { Spin, Icon } from 'antd';
import { isFunction } from 'lodash';
import useLoopRequest from '@/hooks/useLoopRequest.jsx';
import styles from './index.less';

/**
 * @param {Promise} getUrl 获取二维码链接
 * @param {Promise} getScan 获取二维码扫描结果
 * @param {number} qrcodeExpiredTime 二维码过期时间（分钟）
 * @param {number} step 请求间隔（秒）
 * @param {number} width
 * @param {number} height
 *  */
const Qrcode = ({
  width = 240,
  height = 240,
  step = 1,
  getUrl,
  getScan,
  src,
  qrcodeExpiredTime = 1,
}) => {
  const { startLoop, stopLoop, overdue, pause } = useLoopRequest({
    maxTimer: qrcodeExpiredTime,
    delay: step * 1000,
    request: () => {
      getScan && getScan(stopLoop);
    },
  });

  const [loading, setLoading] = useState(false);
  const [maskQr, setMaskQr] = useState(pause);
  const [url, setUrl] = useState('');

  const getQrcodeUrl = useCallback(
    () => {
      if (isFunction(getUrl)) {
        setLoading(true);
        getUrl()
          .then(({ qrcodeUrl }) => {
            if (qrcodeUrl) {
              setUrl(qrcodeUrl);
              startLoop();
              setLoading(false);
              setMaskQr(false);
            }
          })
          .catch(() => {
            setLoading(false);
            setMaskQr(true);
          });
      } else {
        setUrl(src);
        startLoop();
        setLoading(false);
        setMaskQr(false);
      }
    },
    [getUrl, startLoop],
  );

  useEffect(() => {
    getQrcodeUrl();
  }, []);

  useEffect(
    () => {
      if (overdue) {
        stopLoop();
        setMaskQr(true);
      }
      return () => {
        stopLoop();
      };
    },
    [overdue, stopLoop],
  );

  return (
    <Spin spinning={loading}>
      {url ? (
        <div className={styles.maskQr}>
          {maskQr && (
            <div onClick={getQrcodeUrl}>
              <Icon type="redo" />
            </div>
          )}
          <img width={width} height={height} src={url} alt="" />
        </div>
      ) : (
        <div style={{ height, lineHeight: `${height}px` }}>
          <h3>
            获取二维码失败，请
            <a onClick={getQrcodeUrl}>点击</a>
            重新获取
          </h3>
        </div>
      )}
    </Spin>
  );
};

export default React.memo(Qrcode);
